package com.atguigu.state;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by RUI on 2021/6/15 18:04
 * <p>
 * 计算每个传感器的水位和
 */
public class State_key_reduce {
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);

        env.socketTextStream("hadoop162", 9999)
                .map(value -> {
                    String[] split = value.split(",");
                    return new WaterSensor(split[0], Long.valueOf(split[1]), Integer.valueOf(split[2]));
                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private ReducingState<Integer> reduceSumVc;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        reduceSumVc = getRuntimeContext().getReducingState(new ReducingStateDescriptor<Integer>(
                                "reduceSumVc",
                                Integer::sum,
                                Integer.class
                        ));
                    }

                    @Override
                    public void processElement(WaterSensor ws,
                                               Context ctx,
                                               Collector<String> out) throws Exception {

                        reduceSumVc.add(ws.getVc());
                        out.collect(ctx.getCurrentKey()+": "+reduceSumVc.get());

                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
